import {ColumnInfo} from 'vxe-table/types/column'
import {TableHeadItem} from './Config'
import typeOfUtils from '@/utils/type-of-utils'

export class DefaultFormatter {

  private static readonly defaultFormatterCom = [
    'ElSelect',
  ]

  public static get<T>(item: TableHeadItem<T>): Function {
    if (item?.editRender?.name && DefaultFormatter.defaultFormatterCom.includes(item?.editRender?.name)) {
      const formatterFunction = DefaultFormatter[item.editRender.name](item)
      if (typeOfUtils.isNotEmpty(formatterFunction) && typeOfUtils.isFunction(formatterFunction)) {
        return formatterFunction
      }
    }
    return ({cellValue, row, column}): string => {
      return cellValue
    }
  }

  private static ElSelect<T>(item: TableHeadItem<T>) {
    function getDefaultsFormatter() {
      return (cellValue: any, row: T, column: ColumnInfo) => {
        let allOptions = []
        const optionGroups = item?.editRender?.optionGroups
        const optionGroupProps = item?.editRender?.optionGroupProps
        const optionProps = item?.editRender?.optionProps || {label: 'label', value: 'value'}
        // @ts-ignore
        allOptions = item?.editRender?.options || []
        if (optionGroups) {
          const groupOptions = optionGroupProps?.options || 'options'
          // @ts-ignore
          allOptions = optionGroups?.map(i => i[groupOptions])?.flat()
        }
        if (typeOfUtils.isArray(cellValue)) {
          // @ts-ignore
          return allOptions?.filter(i => cellValue?.includes(i[optionProps.value]))?.map(i => i[optionProps.label])?.join(',')
        }
        // @ts-ignore
        return allOptions?.filter(i => cellValue === i[optionProps.value])?.map(i => i[optionProps.label])?.join(',')
      }
    }

    let formatter = item?.formatter
    if (!formatter || typeOfUtils.isNotFunction(formatter)) {
      formatter = ({cellValue, row, column}) => {
        return getDefaultsFormatter()(cellValue, row, column)
      }
    }
    return formatter
  }
}
